package design_patterns;

/**
 * 简单工厂模式
 */
public class SimpleFactoryPattern {
    public static Operation createOperation(String operate) {
        Operation oper = null;
        switch (operate) {
            case "+":
                oper = new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;
            case "/":
                oper = new OperationDiv();
                break;
            default:
                break;
        }
        return oper;
    }

    public static void main(String[] args) throws Exception {
        Operation oper = SimpleFactoryPattern.createOperation("+");
        oper.setNumberA(1);
        oper.setNumberB(2);
        double result = oper.getResult();
        System.out.println(result);
    }
}
/**
 * 计算类
 */
abstract class Operation {
    private double numberA = 0;
    private double numberB = 0;

    /**
     * 计算结果
     * @return 结果
     */
    public abstract double getResult() throws Exception;

    public double getNumberA() {
        return numberA;
    }

    public void setNumberA(double numberA) {
        this.numberA = numberA;
    }

    public double getNumberB() {
        return numberB;
    }

    public void setNumberB(double numberB) {
        this.numberB = numberB;
    }
}

class OperationAdd extends Operation {

    @Override
    public double getResult() {
        return getNumberA() + getNumberB();
    }
}
class OperationSub extends Operation {

    @Override
    public double getResult() {
        return getNumberA() - getNumberB();
    }
}
class OperationMul extends Operation {

    @Override
    public double getResult() {
        return getNumberA() * getNumberB();
    }
}
class OperationDiv extends Operation {

    @Override
    public double getResult() throws Exception {
        if (getNumberB() == 0) {
            throw new Exception("除数不能为零");
        }
        return getNumberA() / getNumberB();
    }
}